package application.controller.server;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import middleware.datacontainer.groupPropertiesChange.GroupPropertiesContainer;
import model.dao.DAOFactory;
import model.dao.GroupDAO;
import model.Group;

import java.util.HashMap;

import application.exceptions.DatabaseException;
import application.exceptions.InsufficientClientRightsException;
import application.exceptions.SessionException;

public class UseCaseControllerGroupPropertiesChange extends AbstractUseCaseController{
	public UseCaseControllerGroupPropertiesChange(){
		super();
		
		if(_allowedRoles == null){
			String[] roles = {"Admin"};
			_allowedRoles = Arrays.asList(roles);
		}
	}
	
	
	public List<GroupPropertiesContainer> getGroupProperties(String sessionId, String ip)
			throws SessionException, InsufficientClientRightsException{		
		checkLogin(sessionId, ip);
		
		List<Group> groups = DAOFactory.getInstance().getGroupDAO().findAll();
		
		List<GroupPropertiesContainer> list = new ArrayList<GroupPropertiesContainer>();
		
		for (Group group : groups){
			GroupPropertiesContainer gpc = new GroupPropertiesContainer(group.getId(),group.getDescription(), group.getLoanDurationInDays(),
					group.getAnnualFee(), group.getLendingExtensionInDays(), group.getAllowedNoOfExtensions());
			list.add(gpc);
		}
		
		return list;
	}
	
	
	public void saveGroupProperties(String sessionId, String ip, List<GroupPropertiesContainer> groupProperties)
			throws SessionException, InsufficientClientRightsException, DatabaseException{
		checkLogin(sessionId, ip);
		GroupDAO groupDAO = DAOFactory.getInstance().getGroupDAO();
		
		for (GroupPropertiesContainer gpc : groupProperties){
			
			Group group = groupDAO.findById(gpc.getId(), false);
			group.setLoanDurationInDays(gpc.getLoanDuration());
			group.setAnnualFee(gpc.getAnnualFee());
			group.setLendingExtensionInDays(gpc.getLendingExtension());
			group.setAllowedNoOfExtensions(gpc.getAllowedNoOfExtension());
			
			groupDAO.makePersistent(group);
		}
	}
}
